package com.itkongxiaoyi.service.impl;

import com.itkongxiaoyi.entity.Student;
import com.itkongxiaoyi.mapper.StudentBatchMapper;
import com.itkongxiaoyi.service.StudentBatchService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentBatchServiceImpl implements StudentBatchService {
    @Autowired
    private StudentBatchMapper studentBatchMapper;
    @Override
    public int importStudents(MultipartFile file) {
        List<Student> studentList = new ArrayList<>();
        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < rowCount; i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                Student student = new Student();
                student.setStudentNo(getCellValueAsString(row.getCell(0)));
                student.setName(getCellValueAsString(row.getCell(1)));
                student.setIdCard(getCellValueAsString(row.getCell(2)));
                student.setAdmissionYear(getCellValueAsInt(row.getCell(3)));
                student.setCollege(getCellValueAsString(row.getCell(4)));
                student.setMajor(getCellValueAsString(row.getCell(5)));
                student.setClassName(getCellValueAsString(row.getCell(6)));
                student.setGender(getCellValueAsInt(row.getCell(7)));
                student.setAge(getCellValueAsInt(row.getCell(8)));
                student.setPhone(getCellValueAsString(row.getCell(9)));
                student.setScore(getCellValueAsInt(row.getCell(10)));
                student.setTime(getCellValueAsInt(row.getCell(11)));
                student.setCreateTime(LocalDateTime.now());
                student.setUpdateTime(LocalDateTime.now());
                studentList.add(student);
            }
            return studentBatchMapper.batchInsert(studentList);
        } catch (IOException e) {
            throw new RuntimeException("导入文件解析失败", e);
        }
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((int) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }

    }

    private int getCellValueAsInt(Cell cell) {
        if (cell == null) {
            return 0; // 空单元格返回默认值0，可根据需求修改
        }

        CellType cellType = cell.getCellType();
        switch (cellType) {
            case NUMERIC:
                // 处理数值类型
                if (DateUtil.isCellDateFormatted(cell)) {
                    throw new IllegalArgumentException("日期格式的单元格无法转换为整数");
                }
                double numericValue = cell.getNumericCellValue();
                int intValue = (int) numericValue;

                // 检查是否有小数部分丢失（例如1.5会被截断为1）
                if (Math.abs(numericValue - intValue) > 0.000001) {
                    throw new IllegalArgumentException("小数部分被截断：" + numericValue);
                }
                return intValue;

            case STRING:
                // 处理字符串类型
                String strValue = cell.getStringCellValue().trim();
                if (strValue.isEmpty()) {
                    return 0; // 空字符串返回默认值0
                }
                try {
                    return Integer.parseInt(strValue);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("无法将字符串转换为整数：" + strValue, e);
                }

            case BOOLEAN:
                // 处理布尔类型（true→1，false→0）
                return cell.getBooleanCellValue() ? 1 : 0;


            default:
                return 0; // 其他类型返回默认值0
        }
    }
}
